#include <curses.h>
#include <stdlib.h>
#include <string.h>
#include "../include/f3.h"
/*#define k 3*/
#define DIS_COLS 8
#define COL_MAX 12
#define PRO_NUM 10
typedef struct
{
	char hostname[20];
	int pid[500];
	float cpu[500];
	float mem[500];
	float max,min,ave;
}COMPUTER;

int float2graph(float in,int x,int y,int my) /*横式*/
{
	in>0.1 && mvaddstr(x,y++,"|");
	float max = COL_MAX;
	int len=(in/max)*(my-y-3),i;
	for(i=0;i<len;i++)
	{
		mvprintw(x,y+i,"|");
	}
	mvaddstr(x,y+i," ");
	mvprintw(x,y+i+1,"%.1f",in);
	return 0;	
}

int float2graph2(float in,int x,int y,float maxin) /*竖式*/
{
	mvaddch(x--,y,ACS_HLINE);
	float max = maxin+5;
	int high = (in/max)*(x-3),i;
	for(i=0;i<high;i++)
	{
		mvaddch(x-i,y,ACS_HLINE);

	}
	mvprintw(x-i,y,"%.1f",in);
	return 0;
}

int InitCOMPUTER(FILE *fp,COMPUTER *in)	/*初始,从文件读入Structure*/
{
	if(fp==NULL)
		return 0;
	memset(in->cpu,-1,500);
	memset(in->pid,-1,500);
	file2float(fp,in->cpu,in->pid);
	GetMMA(in->cpu,&(in->max),&(in->min),&(in->ave));
	return 0;
}
int DrawScr(COMPUTER *in)	/*Stucture输出*/
{
	clear();
	int mx,my,x,y,i,col_len;
	getmaxyx(stdscr,mx,my);
	col_len = (my-6)/COL_MAX;
	x = mx-4;
	y = 3;
	box(stdscr, ACS_VLINE, ACS_HLINE); /*draw a box*/
	for(i=y;i<my-3;i++)
		mvaddch(x,i,ACS_HLINE);
	for(i=0;i<COL_MAX&&in->cpu[i]>1e-6;i++)
	{
		mvprintw(x+1,y+col_len*i,"%5d",in->pid[i]);
		float2graph2(in->cpu[i],x-1,y+col_len*i+2,in->cpu[0]);
	}
	
	attron(A_REVERSE);
	mvprintw(1,my-20,"Computer:%s",in->hostname);
	mvaddstr(mx-2,3,"Press anykey to Quit...");
	mvprintw(mx-2,my-30,"Max:%4.1f  Min:%4.1f  Ave:%4.1f",in->max,in->min,in->ave);
	attroff(A_REVERSE);
	refresh();
	return 1;
}

int main()
{
	char cmd[50]="ps aux|sort -nr -k 3|head -";
	COMPUTER local;
	strcpy(local.hostname,"Test");
	FILE *fp;
	initscr();
	noecho();
	strcat(cmd,"19");
	while(!kbhit())
	{
		fp=popen(cmd,"r");
		InitCOMPUTER(fp,&local);
		DrawScr(&local);
		pclose(fp);
		sleep(1);
	}
	getchar();
	endwin();
	return 0;
} 
